package com.distributed.tcp.manager;

import com.distributed.tcp.config.TcpServerProperties;
import com.distributed.tcp.server.NettyServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;

@Slf4j
@Component
public class PortManager {

    // 端口对应的服务器
    private final Map<Integer, NettyServer> portServers = new ConcurrentHashMap<>();
    
    @Resource
    private TcpServerProperties tcpProperties;
    
    @Resource
    private ThreadPoolManager threadPoolManager;
    
    @Resource
    private MessageHandlerFactory messageHandlerFactory;

    @Resource
    private DeviceConnectionManager deviceConnectionManager;

    /**
     * 初始化端口
     */
    @PostConstruct
    public void init() {
        // 尝试注册初始端口
        if (tcpProperties.getInitialPorts() != null) {
            tcpProperties.getInitialPorts().forEach(this::startPortServer);
        }
        
        log.info("端口管理器初始化完成，初始端口: {}", tcpProperties.getInitialPorts());
    }

    /**
     * 启动端口服务器
     */
    private void startPortServer(int port) {
        if (portServers.containsKey(port)) {
            return;
        }
        
        // 获取端口对应的消息处理器
        String handlerType = tcpProperties.getMessageHandlerMapping().getOrDefault(port, "messageExecute");
        MessageHandler messageHandler = messageHandlerFactory.getHandler(handlerType);
        
        // 获取端口对应的线程池
        ExecutorService executor = threadPoolManager.getExecutorForPort(port);
        
        // 创建并启动Netty服务器
        NettyServer server = new NettyServer(
            port, 
            messageHandler,
            executor,
            deviceConnectionManager
        );
        
        new Thread(() -> {
            try {
                server.start();
                portServers.put(port, server);
                log.info("端口{}服务器启动成功", port);
            } catch (Exception e) {
                log.error("端口{}服务器启动失败", port, e);
            }
        }).start();
    }
}
